const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "空间预约", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent'
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    dateList: [{
        id: 0,
        weekDay: '周一',
        createtime: '2024.10.12',
        status: '可预约',
        check: false, // 勾选
        type: 1, // 1是可以预约，2是预约已满
      },
      {
        id: 1,
        weekDay: '周一',
        createtime: '2024.10.12',
        status: '暂停预约',
        check: false,
        type: 2,
      },
      {
        id: 2,
        weekDay: '周一',
        createtime: '2024.10.12',
        status: '预约已满',
        check: false,
        type: 3,
      },
      {
        id: 4,
        weekDay: '周一',
        createtime: '2024.10.12',
        status: '可预约',
        check: false,
        type: 1,
      },
    ],
    timelist: [{
        id: 1,
        time: '08:00',
        check: false
      },
      {
        id: 2,
        time: '09:00',
        check: false
      },
      {
        id: 3,
        time: '10:00',
        check: false
      },
      {
        id: 4,
        time: '11:00',
        disable: true,
        check: false
      },
      {
        id: 5,
        time: '12:00',
        disable: true,
        check: false
      },
      {
        id: 6,
        time: '13:00',
        disable: true,
        check: false
      },
      {
        id: 7,
        time: '14:00',
        check: false
      },
      {
        id: 8,
        time: '15:00',
        check: false
      },
      {
        id: 9,
        time: '16:00',
        check: false
      },
      {
        id: 10,
        time: '17:00',
        check: false
      }
    ],
    siteInfo:[],
    name: '', // 姓名
    num: '', // 人数
    remark: '', // 备注
    distextarea: true,
    id: 0, //空间id
  },

  getDocumentRectInfo(id, target) {
    return new Promise((resolve, reject) => {
      const query = wx.createSelectorQuery().in(target)
      query.select(id).boundingClientRect()
      query.exec(function (res) {
        if (res === null) reject(new Error('获取dom元素信息失败'))
        resolve(res[0])
      })
    })
  },
  async onPageScroll(t) {
    const textareaTop = await this.getDocumentRectInfo('.textarea', this)
    const btnTop = await this.getDocumentRectInfo('.publicBtnDom', this)
    console.log(textareaTop.top + 40)
    console.log(btnTop)
    if (textareaTop.top + 40 > btnTop.top) {
      console.log(1)
      this.setData({
        distextarea: true
      })
    } else {
      console.log(2)
      this.setData({
        distextarea: false
      })
    }

    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },
  // 选择时间段
  clickTime(e) {
    const item = e.currentTarget.dataset.item
    if (item.disable) {
      return app.showTip('不能选择');
    }
    const index = this.data.timelist.findIndex(el => el.id === item.id)
    // 有第二个点
    if (this.data.timelist.filter(el => el.check).length === 1) {
      // 第一个点的位置
      const one = this.data.timelist.find(el => el.check).id
      // 第二个点的位置
      const two = this.data.timelist[index].id
      // 2点之间数据
      const newlist = one > two ? this.data.timelist.slice(two - 1, one) : this.data.timelist.slice(one - 1, two)
      if (newlist.some(el => el.disable)) {
        return app.showTip('不能选择');
      }
      // 点击同一个点
      if (one === two) {
        this.data.timelist[index].check = !this.data.timelist[index].check
      } else {
        this.data.timelist.forEach(el => {
          if (one > two) {
            if (el.id >= two && el.id <= one) {
              el.check = true
            }
          } else {
            if (el.id >= one && el.id <= two) {
              el.check = true
            }
          }
        })
      }
    } else if (this.data.timelist.filter(el => el.check).length >= 2) {
      this.data.timelist.forEach(el => {
        el.check = false
      })
      this.data.timelist[index].check = true
    } else {
      // 单点
      this.data.timelist[index].check = !this.data.timelist[index].check
    }
    this.setData({
      timelist: this.data.timelist
    })
  },
  //选择日期
  chooseDate(e) {
    let that = this;
    let item = e.currentTarget.dataset.item;
     if (item.type == 2) {
      app.showTip('抱歉,您选择的日期已暂停预约了哦,请选择其他日期预约');
      return;
    }else if (item.type == 3) {
      app.showTip('抱歉,您选择的日期预约人数已满了哦,请选择其他日期预约');
      return;
    }
    // 可以多选时间
    let index = this.data.dateList.findIndex(el => el.id === item.id)
    this.data.dateList[index].check = !this.data.dateList[index].check
    // 只能单选
    this.data.dateList.forEach(el=>{
      el.check=false
      if(el.id===item.id){
        el.check=!el.check
      }
    })
    that.setData({
      dateList: this.data.dateList
    });

    //后台请求刷新时间段
    wx.showLoading({
      title: '时间段刷新中...'
    });
        wx.request({
              url: that.data.baseUrl + 'checkSiteSjd.php',
              method: 'POST',
              data: {
                'createtime': item.ymd,
                'id':that.data.id
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                wx.hideLoading();
                if(res.data.status==1){
                  //后台请求成功
                  that.setData({
                    timelist:res.data.timeList
                  });
                }else{
                   app.showTip(res.data.msg);
                }
              },
              fail: function (res) {
                wx.hideLoading();
                app.showTip('服务器繁忙,请稍候重试');
              }
            });

  },

  //预约
  order() {
    let that = this;
    if (!this.data.dateList.filter(el => el.check).length) {
      app.showTip("请选择日期");
      return;
    }
    if (this.data.timelist.filter(el => el.check).length < 2) {
      app.showTip("请选择时间段(区间)");
      return;
    }
    if (this.data.name === '') {
      app.showTip("请输入活动名称");
      return;
    }
    if (this.data.num === '') {
      app.showTip("请输入人数");
      return;
    }
    if (this.data.num<=0) {
      app.showTip("请输入有效的人数");
      return;
    }
    if(parseInt(this.data.num)>parseInt(that.data.siteInfo['people_number'])){
      app.showTip("此空间容量不能超过"+that.data.siteInfo['people_number']+'人哦');
      return;
    }

    //获取选择的日期
    var dateList = that.data.dateList;
    var yyTime = '';
    for(var i=0;i<dateList.length;i++){
      if(dateList[i]['check']){
        yyTime = dateList[i]['ymd'];
        break;
      }
    }

    //获取选择的时间段
    var yyStartSjd = '';
    var yyEndSjd ='';
    var timelist = that.data.timelist;
    var rowFlag=0;
    for(var j=0;j<timelist.length;j++){
      if(timelist[j]['check']){
        if(rowFlag==0){
          yyStartSjd = timelist[j]['time'];
          rowFlag++
        }else if(rowFlag>0){
          yyEndSjd = timelist[j]['time'];
        }
      }
    }

    //后台提交预约数据
    wx.showLoading({
      title: '信息提交中...'
    });

       wx.request({
        url: that.data.baseUrl + 'addSiteBmInfo.php',
        method: 'POST',
        data: {
          openid: that.data.openid,
          id:that.data.id,
          yy_time:yyTime,
          yyStartSjd:yyStartSjd,
          yyEndSjd:yyEndSjd,
          activity_name:that.data.name,
          remark:that.data.remark,
          people_number:that.data.num
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          wx.hideLoading();
          if (res.data.status == 1) {
            wx.redirectTo({
               url: '/pages/orderCenter/siteOrder/spaceDetail/index?orderId='+res.data.orderId
            });
          }else{
            app.showTip(res.data.msg);
          }
        },
        fail: function(res) {
          wx.hideLoading();
          app.showTip('服务器繁忙,请稍候重试');
          return;
        }
      });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    var id = options.id;
    if (id == 0 || id == '' || id == null || id == undefined) {
      app.showTip('抱歉,未获取到空间id哦');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        });
      }, 1400);
    } else {
      that.setData({
        id: id
      });
    }

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');
    // var openid='oZYOb4jQ1cdq3ZdTqRcQX4r_BI5Y'

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getSiteOrderFillInforPageInfo(res.data.openid,id);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getSiteOrderFillInforPageInfo(openid,id);
    }

    //调用分享
    that.getShareInfo();
  },

    //获取本页数据
    getSiteOrderFillInforPageInfo(openid,id) {
      var that = this;
  
      wx.showLoading({
        title: '数据加载中...'
      });
  
      wx.request({
        url: that.data.baseUrl + 'getSiteOrderFillInforPageInfo.php',
        method: 'POST',
        data: {
          openid: openid,
          id:id
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          wx.hideLoading();
          if (res.data.status == 1) {
            //后台请求成功
            that.setData({
              dateList:res.data.dateList,
              timelist:res.data.timeList,
              siteInfo:res.data.siteInfo
            });
          } else {
            //后台请求失败
            app.showTip(res.data.msg);
            setTimeout(function () {
              wx.navigateBack({
                delta: 1
              });
            }, 1400);
            return;
          }
        },
        fail: function(res) {
          wx.hideLoading();
        }
      });
    },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/lifeService/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})